<?

/* ShopModel model class.
 * This class contains data model implementation code.
 *
 */ 
class ShopModel extends AGModel
{
  // model data
  var $data;

  function __construct($modelName) 
  {
    parent::__construct($modelName);
  }
  
  function sellItem($itemId, &$character)
  {
    if (!isset($character->invList)) $character->getInventory();
    $sellItem = $character->invList[$itemId];
    if (sizeof($sellItem) == 0 || $sellItem['i_value'] <= 0)
    {
      return('You cannot sell that!');
    }
    else
    {
      // reduce the quantity
      $character->addInventory($sellItem, -1);
      // increase gold
      $character->addInventory(array('i_key' => 0), round($sellItem['i_value']/2));
      // unset in order to force inventory reload
      $character->saveCharacter();      
      return('You sold 1x <b>'.$sellItem['i_name'].'</b> for <b>'.round($sellItem['i_value']/2).'</b> gold.');
    }        
  }

  function buyItem($itemId, &$character)
  {
    if (!isset($character->invList)) $character->getInventory();
    $money = $character->getMoney();
    $itemDS = DB_GetDataset('items', $itemId);
    if ($money < $itemDS['i_value'])
    {
      return('You cannot buy that because you are too poor!');
    }
    else
    {
      $qty = 1;
      $character->addInventory(array('i_key' => 0), -$itemDS['i_value']);
      
      // now, let's see if this item does anything on buy
      $itemStats = TextToStringList($itemDS['i_properties']);
      foreach($itemStats as $k => $v)
      {
        if (cutSegment('.', $k) == 'buy')
        {
          $qty = 0;
          $character->stats[$k.'.current'] += $v;
          if ($character->stats[$k.'.current'] > $character->getCharacterStat($k, ',.effective'))
            $character->stats[$k.'.current'] = $character->getCharacterStat($k, ',.effective');
          $character->dirtyFlag = true;
        }
      }
      
      if ($character->dirtyFlag == true)
      {
        $character->saveCharacter();      
      }      

      // modify quantity in inventory
      if ($qty != 0) 
        $character->addInventory($itemDS, $qty);
        
      $equipMessage = '';
      if ($itemDS['i_type'] == 'wearable')
        $equipMessage = '<br/>This item can be worn. Click here to 
          <a href="'.actionUrl('index', 'character', 'on='.$itemDS['i_key']).'" class="linkbutton">put it on</a> now!';

      // unset in order to force inventory reload
      unset($character->invList);
      return('You just bought 1x <b>'.$itemDS['i_name'].'</b> for <b>'.$itemDS['i_value'].'</b> gold. '.
        $equipMessage);
    }
  }
}


?>
